package com.zyl.blog.rbac.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @version v1.0
 * @ProjectName: Personal_Blog_Server
 * @Package: com.zyl.rbac.config
 * @ClassName: RedisConfig
 * @Description: Redis配置类，兼容Spring Data Redis 3.0+版本
 * @Author FinalFantasy
 * @Date 2025/8/11-09:12
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        /* 设置连接工厂 */
        template.setConnectionFactory(connectionFactory);

        /* 配置序列化器（避免 key/value 乱码） */
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        /* key 序列化 */
        template.setKeySerializer(stringSerializer);
        /* hash key 序列化 */
        template.setHashKeySerializer(stringSerializer);

        /* 配置value序列化器 */
        /* 使用构造函数传入ObjectMapper，替代已弃用的setObjectMapper方法 */
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL);

        /* 通过构造函数设置ObjectMapper */
        Jackson2JsonRedisSerializer<Object> jsonSerializer = new Jackson2JsonRedisSerializer<>(mapper, Object.class);

        template.setValueSerializer(jsonSerializer);
        template.setHashValueSerializer(jsonSerializer);

        /* 执行初始化 */
        template.afterPropertiesSet();
        return template;
    }

    /* 新增StringRedisTemplate的Bean定义 */
    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(connectionFactory);
        return template;
    }
}
